package day1220;

import java.sql.*;

public class UserDao {
    public static void main(String[] args) throws Exception {
        UserDao  dao=new UserDao();
        UserData  user=new UserData("admin","234");
        dao.addUserData(user);
    }

    public  void  addUserData(UserData  user) throws Exception {
//        if(isExists(user)){
//            throw new Exception("用户名被占用");
//        }
        Class.forName("com.mysql.cj.jdbc.Driver");//1. Driver
        Connection conn =DriverManager.getConnection(//2.连接数据库  url   账号  密码
                "jdbc:mysql://localhost:3306/chat_room?serverTimezone=GMT%2B8&useSSL=false",
                "root","root");
        PreparedStatement stmt=conn.prepareStatement(
                "insert into char_user (username,password)value(?,?)");//3.发送sql到mysql并预编译
        stmt.executeUpdate();//4.执行sql
        conn.close();//5.关闭连接
    }

    public boolean findUser(String username, String password) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");//1. Driver
        Connection conn =DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/chat_room?serverTimezone=GMT%2B8&useSSL=false",
                "root","root");//2.连接数据库  url   root  root
        PreparedStatement stmt=
                conn.prepareStatement(
                        "select * from  char_user where username=? and password=?");//3.预编译对象(sql语句传输给MySQL)
        ResultSet rs=stmt.executeQuery();//4.调用预编译对象的executeQuery()执行SQL， ResultSet查询结果
        if(rs.next()){//5.获取：  ResultSet.getXXX()
            return  true;
        }
        conn.close();//6.关闭数据库
        return  false;
    }
}